/*
 * PaymentServlet.java
 *
 * 6�~12��03�� �P�d�, �U��4:06
 */

package servlet;

import beans.PaymentBean;
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 *
 * @author HOME
 * @version
 */
public class PaymentServlet extends HttpServlet {
    
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        
        String itemID = PaymentBean.createPayment((String)request.getSession().getAttribute("username"), request);
        if (itemID != null) {
            response.getWriter().println("<h3>Item'"+itemID+"'is out of stock!</h3>");
            response.sendRedirect("PaymentFailed.jsp?itemID="+itemID);
            //http://localhost:8080/FYP/LoginServlet?name=abc&password=123
            return;
        }else {
            Cookie[] cookies = request.getCookies();
            for (int i=0; i<cookies.length; i++) {
                Cookie myCookie = cookies[i];
                String name = myCookie.getName();
                myCookie.setMaxAge(0);
                response.addCookie(myCookie);
                if ( name.indexOf(".ID") != -1) {
                    //out.print(name);
                    myCookie.setMaxAge(0);
                    response.addCookie(myCookie);
                }
            }
            response.sendRedirect("PaymentDone.jsp");
            return;
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
